import api from './axiosConfig';
import fastApi from './fastApiConfig';

// 将FastAPI预测结果同步到Windows数据库
export const syncPredictionToWindowsDB = async (userId, predictionResult) => {
  try {
    // 预处理预测结果，确保数据格式正确
    let formattedResult = predictionResult;
    
    // 如果预测结果是数组格式，提取第一个元素
    if (Array.isArray(predictionResult) && predictionResult.length > 0) {
      formattedResult = {
        ...predictionResult[0],
        originalArray: predictionResult // 保留原始数组数据
      };
    }
    
    // 调用SpringBoot接口，将预测结果存入Windows数据库
    // 使用后端提供的/api/health-risk/add接口
    const healthRiskData = {
      userId: Number(userId),
      indicatorId: Number(userId), // 设置indicatorId为userId，避免非空约束错误
      cardioRisk: formattedResult.probability || formattedResult.riskValue,
      riskLevel: formattedResult.riskLevel || '未知',
      riskFactors: formattedResult.contributingFactors || '暂无风险因素',
      improvementSuggest: formattedResult.suggestions || '保持健康生活方式',
      predictTime: new Date().toISOString()
    };
    
    const response = await api.post('/health-risk/add', healthRiskData);
    
    console.log('预测结果同步成功:', response.data);
    return response.data;
  } catch (error) {
    console.error('预测结果同步失败:', error);
    
    // 保存到localStorage作为备份
    const backupKey = `prediction_backup_${Date.now()}`;
    localStorage.setItem(backupKey, JSON.stringify({
      userId,
      predictionResult,
      timestamp: new Date().toISOString(),
      syncStatus: 'failed'
    }));
    console.log(`预测结果已保存到localStorage作为备份: ${backupKey}`);
    
    // 不抛出错误，允许流程继续
    return { success: false, message: '同步失败，数据已保存到本地', backupKey };
  }
};

// 定期同步用户数据
export const scheduleDataSync = (userId, interval = 300000) => { // 5分钟同步一次
  const syncFunction = async () => {
    try {
      // 获取最新预测
      const predictionResponse = await fastApi.get(`/predictions/${userId}/latest`);
      if (predictionResponse.data) {
        await syncPredictionToWindowsDB(userId, predictionResponse.data);
      }
    } catch (error) {
      console.error('定时同步失败:', error);
    }
  };
  
  // 立即执行一次
  syncFunction();
  
  // 设置定时任务
  return setInterval(syncFunction, interval);
};

// 尝试重试失败的同步
export const retryFailedSyncs = async () => {
  try {
    // 查找所有备份数据
    const backupKeys = Object.keys(localStorage).filter(key => 
      key.startsWith('prediction_backup_')
    );
    
    for (const key of backupKeys) {
      const backup = JSON.parse(localStorage.getItem(key));
      // 只尝试同步24小时内的备份
      const backupAge = Date.now() - new Date(backup.timestamp).getTime();
      if (backupAge < 24 * 60 * 60 * 1000) {
        console.log(`尝试重新同步备份: ${key}`);
        const result = await syncPredictionToWindowsDB(backup.userId, backup.predictionResult);
        if (result.success !== false) {
          localStorage.removeItem(key);
          console.log(`备份同步成功，已删除: ${key}`);
        }
      } else {
        console.log(`备份已过期，删除: ${key}`);
        localStorage.removeItem(key);
      }
    }
  } catch (error) {
    console.error('重试同步失败:', error);
  }
};